package com.ruoyi.ems.controller;

import com.jnxx.basic.dto.RobotMessage;
import com.jnxx.basic.util.SendRobotMessageUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ems.domain.EmsScoreDetails;
import com.ruoyi.ems.domain.Staff;
import com.ruoyi.ems.service.IEmsScoreDetailsService;
import com.ruoyi.ems.service.IStaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 员工信息Controller
 * 
 * @author sh
 * @date 2023-12-12
 */
@RestController
@RequestMapping("/ems/staff")
public class StaffController extends BaseController
{
    @Autowired
    private IStaffService staffService;

    @Autowired
    private IEmsScoreDetailsService scoreDetailsService;


    @Autowired
    private SendRobotMessageUtil sendRobotMessageUtil;

    /**
     * 查询员工信息列表
     */
    @PreAuthorize("@ss.hasPermi('ems:staff:list')")
    @GetMapping("/list")
    public TableDataInfo list(Staff staff)
    {
        startPage();
        List<Staff> list = staffService.selectStaffList(staff);
        return getDataTable(list);
    }

    /**
     * 导出员工信息列表
     */
    @PreAuthorize("@ss.hasPermi('ems:staff:export')")
    @Log(title = "员工信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Staff staff)
    {
        List<Staff> list = staffService.selectStaffList(staff);
        ExcelUtil<Staff> util = new ExcelUtil<Staff>(Staff.class);
        util.exportExcel(response, list, "员工信息数据");
    }

    /**
     * 获取员工信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ems:staff:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(staffService.selectStaffById(id));
    }

    /**
     * 新增员工信息
     */
    @PreAuthorize("@ss.hasPermi('ems:staff:add')")
    @Log(title = "员工信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Staff staff)
    {
        return toAjax(staffService.insertStaff(staff));
    }

    /**
     * 修改员工信息
     */
    @PreAuthorize("@ss.hasPermi('ems:staff:edit')")
    @Log(title = "员工信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Staff staff)
    {
        return toAjax(staffService.updateStaff(staff));
    }

    /**
     * 删除员工信息
     */
    @PreAuthorize("@ss.hasPermi('ems:staff:remove')")
    @Log(title = "员工信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(staffService.deleteStaffByIds(ids));
    }

    /**
     * 修改分数
     * @param staff
     */
    @Transactional
    @PostMapping("/updateStaffScore")
    public AjaxResult updateStaffScore(@RequestBody Staff staff) {
        try {
            Integer scoreTmp = staff.getScoreTmp();
            String scoreExplainInfo = staff.getScoreExplainInfo();
            Integer score = staff.getScore();
            if (score == null){
                score = 0;
            }
            staff.setScore(score + scoreTmp);
            String reviser = staff.getReviser();
            staffService.updateStaff(staff);

            EmsScoreDetails emsScoreDetails = new EmsScoreDetails();
            // 获取当前登录人名称
//        String createAccount = SecurityUtils.getUsername();
            if (StringUtils.isNotBlank(reviser)){
                emsScoreDetails.setReviser(reviser);
            }
            emsScoreDetails.setExplain(scoreExplainInfo);
            emsScoreDetails.setModifiedPerson(staff.getName());
            emsScoreDetails.setScore(scoreTmp);
            emsScoreDetails.setCreatTime(new Date());
            scoreDetailsService.insertEmsScoreDetails(emsScoreDetails);
            RobotMessage robotMessage = new RobotMessage();
            String text = "";
            if (scoreTmp > 0){
                text = staff.getName() + "增加积分：" + scoreTmp;
            } else {
                text = staff.getName() + "扣除积分：" + Math.abs(scoreTmp);
            }
            robotMessage.setText(text);
//            robotMessage.setUrl("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f5eb4e7f-e602-497a-b403-d080b55854a8");
//            AjaxResult ajaxResult = sendRobotMessageUtil.sendRobotMessage(robotMessage);
//            if (ajaxResult.isError()){
//                logger.error("机器人发送积分信息失败，修改id：{}", emsScoreDetails.getId());
//            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("添加积分失败");
        }

    }


    @PostMapping("/loadAll")
    public List<Staff> loadAll(){
        return staffService.loadAll();
    }
}
